'''
人生苦短，我用Python
班级:1906B
日期:{2020/4/24}
阶段：Python爬虫

'''
from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from myapp.models import ZcUser

def make_password(mypass):
    #实例化
    md5 = hashlib.md5()
    #编码，将pypass强转成字符串，以免编码错误
    mypass_utf8 = str(mypass).encode(encoding='utf-8')
    # 将编码后的结果进行加密
    md5.update(mypass_utf8)
    # 将加密后的结果返回
    return md5.hexdigest()

class UserRegister(APIView):

    def get(self,request):
        # 获取用户名和密码
        username = request.GET.get('username',None)
        password = request.GET.get('password',None)
        print(type(username),username)
        print(type(password),password)
        # 根据用户名查是否有相同的用户名
        user = ZcUser.objects.filter(username=username).first()

        if user:
            # 如果有则返回该用户已存在
            return Response({'code':403,'message':'该用户已存在'})
        # 如果没有则进行入库，并返回注册成功
        user1 = ZcUser(username = username,password=make_password(password))
        print(make_password(password))

        user1.save()
        return Response({'code':200,'message':'注册成功'})

class UserLogin(APIView):
    def get(self,request):
        # 获取用户名和密码
        username = request.GET.get('username',None)
        password = request.GET.get('password',None)
        print(type(username),username)
        print(type(password),password)
        # 查看是否有该用户及密码是否正确
        user = ZcUser.objects.filter(username=username,password=make_password(password)).first()
        print(make_password(password))
        if user:
            # 正确则返回登录成功
            return Response({'code':200,'message':'登陆成功'})
        else:
            # 否则返回，用户名或密码错误
            return Response({'code':403,'message':'您的用户名或密码错误'})



